//
//  NSObject+DJZCoding.m
//  0921Runtime
//
//  Created by 丁建忠 on 15/12/30.
//  Copyright © 2015年 丁建忠. All rights reserved.
//

#import "NSObject+DJZCoding.h"
#import <objc/runtime.h>
@implementation NSObject (DJZCoding)
#pragma mark - 归档反归档
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [self init];
    if (self) {
        unsigned int count = 0;
        objc_property_t *propertyList = class_copyPropertyList([self class], &count);
        for (int i = 0; i < count; i++) {
            objc_property_t property = propertyList[i];
            const char *propertyName = property_getName(property);
            NSString *propertyNameStr = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding];
            //取出值
            id value = [aDecoder decodeObjectForKey:propertyNameStr];
            //通过KVC间接给属性赋值,因为无法直接取到属性
            [self setValue:value forKey:propertyNameStr];
            
        }
        //释放copy的指针
        free(propertyList);
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    unsigned int count = 0;
    objc_property_t *propertyList = class_copyPropertyList([self class], &count);
    for (int i = 0; i < count; i++) {
        objc_property_t property = propertyList[i];
        const char *propertyName = property_getName(property);
        NSString *propertyNameStr = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding];
        id value = [self valueForKey:propertyNameStr];
        [aCoder encodeObject:value forKey:propertyNameStr];
    }
    free(propertyList);
}
@end
